// page/search/search.js
import request from "../../utils/request";

let isSearch = false;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        showKeyword: '',
        hotDetails: [],
        searchKeyWord: '',
        searchIng: false,
        searchResult: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.getDefaultKeyWord();
        this.getHotDetail();
    },
    searchKeyword(event) {
        this.setData({
            searchKeyWord: event.detail.value
        });
        if (event.detail.value !== '') {
            setTimeout((res) => {
                isSearch = true;
            }, 300);
            if (isSearch) {
                this.search();
                isSearch = false;
                this.setData({
                    searchIng: true
                })
            } else {
                return;
            }
        } else {
            this.setData({
                searchIng: false
            })
        }
    },
    // 搜索热点
    searchHot(event) {
        let searchKeyWord = event.currentTarget.id;
        this.setData({
            searchKeyWord,
            searchIng: true,
        });
        this.search()
    },
    cancel() {
        isSearch = false;
        this.setData({
            searchIng: false,
            searchKeyWord: '',
            showKeyword: ''
        });
        this.getDefaultKeyWord();
    },
    toSongDetail(event) {
        let pid = event.currentTarget.id;
        wx.navigateTo({
            url: '/page/songDetail/songDetail?musicId=' + pid
        })
    },
    // 关键字搜索
    async search() {
        let searchData = await request("/search?keywords=" + this.data.searchKeyWord + "&limit=10")
        this.setData({
            searchResult: searchData.result.songs
        })
    },
    // 默认显示搜索
    async getDefaultKeyWord() {
        let defaultData = await request("/search/default");
        this.setData({
            showKeyword: defaultData.data.showKeyword
        })
    },
    // 获取热点信息
    async getHotDetail() {
        let hotDetailData = await request("/search/hot/detail");
        let index = 0;
        let hotDetails = hotDetailData.data.map(item => {
            item.index = index++;
            return item;
        });
        this.setData({
            hotDetails
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    }
})
